import { splitValueAndUnit } from "@/pages/lowCodeEditorPlus/utils/string-operator";
import { InputNumber, Select } from "antd";
import type { GetProps, InputNumberProps } from 'antd';
import { debounce } from "lodash-es";
import { useEffect, useState } from "react";
type GeometryUnitInputNumberType = GetProps<typeof InputNumber>;
export function GeometryUnitInputNumber (props: GeometryUnitInputNumberType){
  const {onChange,value,id} = props
  const [preValue, setPreValue] = useState<number|null>(null);
  const [sufValue, setSufValue] = useState('px');
  useEffect(() => {
    if(typeof value === 'string'){
      const {number,unit} = splitValueAndUnit(value)
      if(number !== null){
        setPreValue(number)
        setSufValue(unit || 'px');
      }
    }else if(typeof value === 'number'){
      setPreValue(value)
    }else{
    }
  }, [value]);
  
  const handleUnitChange= (unitValue: string) => {
    setSufValue(unitValue)
    if(value){
      onChange?.(parseInt(value+'')+unitValue);
    }else{
      onChange?.(value||null);
    }
  };
  const handleValueChange: InputNumberProps['onChange']  = debounce((val) => {
    const res = val ? val+sufValue : null
    onChange?.(res);
  },300)
  const selectAfter = (
    <Select
      defaultValue="px"
      style={{
        width: 70
      }}
      value={sufValue}
      onChange={handleUnitChange}
      options={['px', 'em', '%', 'vw', 'vh'].map((item)=>({value:item,label:item}))}
    />
  );

  return <InputNumber {...props} value={preValue} addonAfter={selectAfter} onChange={handleValueChange}/>;
}